import {Button, Dropdown, Flex, Form, Input, Select, Space, Table, Tag} from "antd";
import {Fragment, useEffect, useRef, useState} from "react";
import {getArticlePageUrl, removeArticleByIdUrl} from "@/api/blog/article.ts";
import EditDialog from "./editDialog.tsx";
import useGetDict from "@/hooks/useGetDict.ts";
import dictTag, {selectOptions} from "@/components/DictTag";
import {DownloadOutlined, DownOutlined, PlusOutlined, RedoOutlined, SearchOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
import {getModalSystemConfig, globalMessageApi, globalModalApi} from "@/components/OpComponent/Message";
import {PageWrapperBox, SearchFormBox, TableContainerBox} from "@/layout/Page";
import {TableRowSelection} from "antd/es/table/interface";

interface DataType {
    // 匹配全部
    [key: string]: any;
}

export default function () {

    const [data, setData] = useState([])
    const [loading, setLoading] = useState(false)
    const [total, setTotal] = useState(0)
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const [queryParams, setQueryParams] = useState({
        pageNum: 1,
        pageSize: 10,
    })

    const dictData = useGetDict("art_category", "art_tag", "status")

    const editDialogRef = useRef<any>(null)

    function getTableDateList() {
        setLoading(true)
        getArticlePageUrl({
            ...queryParams,
            ...form.getFieldsValue()
        }).then((res: any) => {
            setData(res.rows)
            setTotal(res.total)
            setLoading(false)
        })
    }

    const handleRefresh = () => {
        form.resetFields()
        getTableDateList()
    }

    useEffect(() => {
        getTableDateList()
    }, []);


    const handleDelete = async (id: number) => {
        const confirmed = await globalModalApi.confirm(getModalSystemConfig("是否删除该文章?"));
        if (confirmed) {
            removeArticleByIdUrl({artId: id}).then((res: any) => {
                globalMessageApi.success(res.msg)
                getTableDateList()
            })
        }
    }

    const columns: any = [
        {title: "编号", minWidth: 60, dataIndex: "artId", ellipsis: true, align: "center"},
        {title: "文章名称", minWidth: 160, dataIndex: "artTitle", ellipsis: true, align: "center"},
        {
            title: "所在专栏", minWidth: 90, dataIndex: "artCategoryId", ellipsis: true, align: "center",
            render: (text: any) => {
                return dictTag(dictData.art_category, text)
            }
        },
        {
            title: "文章标签",
            minWidth: 90,
            dataIndex: "artTag",
            align: "center",
            ellipsis: true,
            render: (text: any = "") => {
                if (!text) return <>-</>
                const tagList = text.split(",") || []
                return tagList.map((item: any, index: number) => {
                    return <Tag key={index}>{dictTag(dictData.art_tag, item)}</Tag>
                })
            }
        },
        {title: "排序", minWidth: 90, dataIndex: "sort", align: "center"},
        {
            title: "状态",
            minWidth: 90,
            dataIndex: "status",
            align: "center",
            render: (text: any) => {
                return text === 0 ? <Tag color={"warning"}>未发布</Tag> : <Tag color={"success"}>已发布</Tag>
            }
        },
        {title: "创建时间", minWidth: 160, dataIndex: "createTime", ellipsis: true, align: "center"},
        {
            title: "操作",
            minWidth: 160,
            align: "center",
            ellipsis: true,
            fixed: "right",
            render: (record: any, index: number) => {
                return <Space key={index}>
                    <Dropdown
                        menu={{
                            items: [
                                {
                                    key: "1", label: "基础信息", onClick: () => {
                                        editDialogRef.current.openModal(record)
                                    }
                                },
                                {
                                    key: "2", label: "文章内容", onClick: () => {
                                        navigate(`/blog/articles/edit/${record.artId}`)
                                    },
                                },
                                {
                                    key: "3", label: "文章图片", onClick: () => {
                                        navigate(`/blog/articles/picture/${record.artId}`)
                                    },
                                },
                            ]
                        }}
                    >
                        <a>编辑<DownOutlined style={{marginLeft: 2, fontSize: 12}}/></a>
                    </Dropdown>
                    <a onClick={() => handleDelete(record.artId)}>评论</a>
                    <a className={"text-red-500"} onClick={() => handleDelete(record.artId)}>删除</a>
                </Space>
            }
        },
    ];

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    return <PageWrapperBox>
        <SearchFormBox>
            <Form form={form} layout={"inline"} colon={false}>
                <Form.Item name="artTitle" label="文章名称">
                    <Input placeholder="请输入文章名称"></Input>
                </Form.Item>
                <Form.Item name={"artCategoryId"} label="分类专栏">
                    <Select style={{width: 160}} placeholder="请选择专栏">
                        {selectOptions(dictData.art_category)}
                    </Select>
                </Form.Item>
                <Form.Item name={"status"} label="状态">
                    <Select style={{width: 120}} placeholder="请选择状态">
                        {selectOptions(dictData.status)}
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button icon={<SearchOutlined/>} type="primary" onClick={getTableDateList}>查询</Button>
                        <Button icon={<RedoOutlined/>} onClick={handleRefresh}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
        </SearchFormBox>
        <TableContainerBox>
            <Flex align="center" gap="small" style={{marginBottom: 6}}>
                <Button icon={<PlusOutlined/>} type="primary"
                        onClick={() => editDialogRef.current.openModal()}> 新增</Button>
                <Button disabled={selectedRowKeys.length === 0} icon={<DownloadOutlined/>}>导出</Button>
            </Flex>
            <Table
                rowSelection={rowSelection}
                rowKey="artId"
                loading={loading}
                tableLayout="auto"
                dataSource={data}
                columns={columns}
                scroll={
                    {x: 'auto'}
                }
                pagination={{
                    pageSizeOptions: ['10', '20', '30', '40'],
                    showSizeChanger: true,
                    showTotal: () => `共 ${total} 条数据`,
                    total: total,
                    defaultPageSize: 10,
                    defaultCurrent: 1,
                    onChange: (page, pageSize) => {
                        setQueryParams({pageNum: page, pageSize: pageSize})
                    },
                }}
            >
            </Table>
        </TableContainerBox>
        <EditDialog ref={editDialogRef} getList={getTableDateList}/>
    </PageWrapperBox>
}
